package com.xyy.ebattery.tcp.app;

import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;



/**
 * @Description TODO
 * @author JIA BOYAN
 * date 2025/06/16  17.41
 */
@Component
public class ChannelManager {

    private final ConcurrentMap<String, Channel> channelMap = new ConcurrentHashMap<>();

    public void addChannel(Channel channel) {
        String key = channel.remoteAddress().toString();
        channelMap.put(key, channel);
    }

    public void removeChannel(Channel channel) {
        String key = channel.remoteAddress().toString();
        channelMap.remove(key);
    }

    // 广播消息给所有客户端
    public void broadcast(String message) {
        channelMap.values().forEach(channel ->
                channel.writeAndFlush(message)
        );
    }
}